package com.njuse.jvmfinal.Instruction;

import java.nio.ByteBuffer;

import com.njuse.jvmfinal.memory.jclass.JClass;
import com.njuse.jvmfinal.memory.jclass.runtimeConstantPool.constant.Constant;
import com.njuse.jvmfinal.memory.jclass.runtimeConstantPool.constant.ref.ClassRef;
import com.njuse.jvmfinal.runtimestructure.Jarray;
import com.njuse.jvmfinal.runtimestructure.Jframe;
import com.njuse.jvmfinal.runtimestructure.Jlink;

public class MULTIANEWARRAY extends Instruction {
	private int index;
	private int dimension;
	private  int[] count;
	public void readindex(ByteBuffer reader) {
		this.index=(int)reader.getShort();
		this.dimension=(int) reader.get();
	}
	
	public void execute(Jframe frame) {
		Constant classref=frame.getMymethod().getClazz().getRuntimeConstantPool().getConstant(index);
		ClassRef clazzref=(ClassRef) classref;
		JClass targetclass=clazzref.getclass();
        
		count=new int[dimension];
		Object[] stack=frame.getManagestack();
		int top=frame.getStacktop();
		for (int i=dimension-1;i>=0;i--) {
			count[i]=(int)stack[top-1];
			top--;
		}
		Jlink[] links=new Jlink[dimension];
		for (int i=dimension-1;i>=0;i--) {
			if (i==dimension-1) {
			links[i]=new Jlink(count[i],null);
			}else {
			links[i]=new Jlink(count[i],links[i+1]);	
			}
		}
		
		Jarray ref=new Jarray(links[0],0,targetclass.getComponent(),targetclass);
		stack[top]=ref;
		top++;
		frame.setManagestack(stack);
		frame.setStacktop(top);
	}
}
